package org.hhgzs.modules.erp.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hhgzs.modules.erp.constants.BusinessConstants;
import org.hhgzs.modules.erp.entity.Sequence;
import org.hhgzs.modules.erp.exception.JshException;
import org.hhgzs.modules.erp.mapper.SequenceMapper;
import org.hhgzs.modules.erp.service.SequenceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 单据编号表 服务实现类
 * </p>
 *
 * @author peiqy
 * @since 2021-07-14
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SequenceServiceImpl extends ServiceImpl<SequenceMapper, Sequence> implements SequenceService {

    private final SequenceMapper sequenceMapper;
    /**
     * 创建一个唯一的序列号
     * */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public String buildOnlyNumber(String seqName){
        Long buildOnlyNumber=null;
        synchronized (this){
            try{
                sequenceMapper.updateBuildOnlyNumber(seqName); //编号+1
                buildOnlyNumber= sequenceMapper.getBuildOnlyNumber(seqName);
            }catch(Exception e){
                JshException.writeFail(log, e);
            }
        }
        if(buildOnlyNumber<BusinessConstants.SEQ_TO_STRING_MIN_LENGTH){
            StringBuffer sb=new StringBuffer(buildOnlyNumber.toString());
            int len=BusinessConstants.SEQ_TO_STRING_MIN_LENGTH.toString().length()-sb.length();
            for(int i=0;i<len;i++){
                sb.insert(0,BusinessConstants.SEQ_TO_STRING_LESS_INSERT);
            }
            return sb.toString();
        }else{
            return buildOnlyNumber.toString();
        }
    }
}
